var express = require("express");
var port = process.env.PORT || 2000;
var app = express();
var path = require("path");
var bodyParser = require("body-parser");
var fs = require("fs"); // 引入fs模块
require("body-parser-xml")(bodyParser);

Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.use(
  bodyParser.xml({
    limit: "100MB", // Reject payload bigger than 1 MB
    xmlParseOptions: {
      normalize: true, // Trim whitespace inside text nodes
      normalizeTags: true, // Transform tags to lowercase
      explicitArray: false, // Only put nodes in array if >1
    },
  })
);

app.use(bodyParser.json({ limit: "100MB" }));

app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, "public")));

app.listen(port);

console.log("app on port " + port);
var resultData = {
  code: 1,
  msg: "日志上传成功",
};
var ToGB2312 = function (str) {
    return unescape(str.replace(/\\u/gi, '%u'));
}
var logWrite = function (log) {
  // 写入文件内容（如果文件不存在会创建一个文件）
  // 传递了追加参数 { 'flag': 'a' }
  fs.writeFile("./log.txt", ToGB2312(log), { flag: "a" }, function (err) {
    if (err) {
      throw err;
    }
  });
};""

app.post("/logUpload", function (req, res) {
  logWrite("\n\n"+ new Date().Format("yyyy-MM-dd hh:mm:ss")+" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" );
  
  logWrite("\n\n"+ new Date().Format("yyyy-MM-dd hh:mm:ss")+"\t _did: \t" + req.body._did);
  logWrite("\n\n"+ new Date().Format("yyyy-MM-dd hh:mm:ss")+"\t href: \t" + req.body.href);
  logWrite("\n\n"+ new Date().Format("yyyy-MM-dd hh:mm:ss")+"\t cookie: \t" + req.body.cookie);
  logWrite("\n\n"+ new Date().Format("yyyy-MM-dd hh:mm:ss")+"\t localStorage: \t" + req.body.localStorage);
  logWrite("\n\n"+ new Date().Format("yyyy-MM-dd hh:mm:ss")+"\t sessionStorage: \t" + req.body.sessionStorage);
  logWrite("\n\n"+ new Date().Format("yyyy-MM-dd hh:mm:ss")+"\t userAgent: \t" +req.body.userAgent);
  logWrite("\n\n"+ new Date().Format("yyyy-MM-dd hh:mm:ss")+"\t "+req.body.logType+": \t" + req.body.content);
  
  res.writeHead(200, { "Content-Type": "application/json" });
  res.end(JSON.stringify(resultData));
});
